shell 练习-判断日期合法

用shell脚本判断输入的日期是否合法。就是判断日期是都是真实的日期,比如20170110就是合法日期,20171332就不合法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
#check date
if [ $# -ne 1 ] || [ ${#1} -ne 8 ]
then
echo "Usage: bash $0 yyyymmdd"
exit 1
fi
datem=$1
year=${datem:0:4}
month=${datem:4:2}
day=${datem:6:2}
if echo $day|grep -q '^0'
then
day=`echo $day |sed 's/^0//'`
fi
if cal $month $year >/dev/null 2>/dev/null
then
daym=`cal $month $year|egrep -v "$year|Su"|grep -w "$day"`
if [ "$daym" != "" ]
then
echo ok
else
echo "Error: Please input a wright date."
exit 1
fi
else
echo "Error: Please input a wright date."
exit 1
fi